package com.base.app_core.View.dialog;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.base.app_core.App;
import com.base.app_core.R;
import com.base.app_core.R2;
import com.base.app_core.View.adapter.RegionAdapter;
import com.base.app_core.base.ActionPacketView;
import com.base.app_core.base.impl.BaseActivity;
import com.base.app_core.ioc.module.BaseModule;
import com.base.app_core.model.Paginated;
import com.base.app_core.model.Region;
import com.base.app_core.service.pressenter.XYBUPressenter;
import com.base.app_core.service.user.model.Address;
import com.base.app_core.util.XYBAUtils;

import java.util.Collection;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;

/**
 * Created by xiangheng.song on 2017/3/10.
 */

public class SelectRegionWindow extends PopupWindow implements ActionPacketView.UserView{

    private OnRegionSelectListener listener;
    private BaseActivity activity;
    private int selectDeep=3;

    public void setSelectDeep(int selectDeep) {
        this.selectDeep = selectDeep;
    }


    @BindView(R2.id.nav)
    LinearLayout navLayout;

    @BindView(R2.id.list)
    ListView regionList;

    private RegionAdapter regionAdapter;

    @Inject
    XYBUPressenter regionService;

    private Long[] ids = {1L, null, null, null};
    private String[] names = {"中国", null, null, null};
    private int mType=0;

    public void setmType(int mType) {
        this.mType = mType;
    }

    public void setupId(long... ids){
        if(ids == null){
            return;
        }
        for(int i = 0; i < ids.length; i++){
            this.ids[i+1] = ids[i];
        }
    }
    public void setupName(String... names){
        if(names == null){
            return;
        }
        for(int i = 0; i < names.length; i++){
            this.names[i+1] = names[i];
        }
    }

    public SelectRegionWindow(BaseActivity activity){
        super(activity);
        this.activity = activity;
        View view = LayoutInflater.from(activity).inflate(R.layout.region, null);
        LinearLayout data_container=(LinearLayout) view.findViewById(R.id.data_container);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                close();
            }
        });
        data_container.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        setContentView(view);
        ButterKnife.bind(this, view);
        App.getApp().getAppComponent().plus(new BaseModule(this)).inject(this);
        if(regionService!=null)regionService.attachView(this);
        setHeight((int)(XYBAUtils.getScreenSize().y));
        LinearLayout.LayoutParams layoutParams= (LinearLayout.LayoutParams) data_container.getLayoutParams();
        layoutParams.height=(int)(XYBAUtils.getScreenSize().y*0.6);
        data_container.setLayoutParams(layoutParams);
        setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);

        setBackgroundDrawable(new ColorDrawable(0x33000000));
        setAnimationStyle(R.style.Animation_AnimBottom);

        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1.0f);
            }
        });
        setFocusable(true);
        setOutsideTouchable(true);
        update();
    }

    @OnClick(R2.id.close)
    public void close(){
        dismiss();
    }

    public void setOnRegionSelectListener(OnRegionSelectListener listener){
        this.listener = listener;
    }

    @Override
    public void doUpdateInfoSuccess() {

    }

    private void updateList(){
        for(int i = ids.length-1; i > 0; i--){
            Long parentId = ids[i-1];
            if(parentId != null){
                initRegionList(parentId, ids[i]);
                break;
            }
        }
    }

    private void updateNav(){
        navLayout.removeAllViewsInLayout();
        for(int i = 1; i < names.length; i++){
            View layout = LayoutInflater.from(activity).inflate(R.layout.region_nav, null);
            TextView textView = (TextView) layout.findViewById(R.id.text);
            textView.setText(names[i] == null ? "请选择" : names[i]);
            navLayout.addView(layout);
            layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(v.findViewById(R.id.base_line).getVisibility() == View.VISIBLE){
                        return;
                    }
                    for(int j = 0; j < navLayout.getChildCount(); j++){
                        View baseLine = navLayout.getChildAt(j).findViewById(R.id.base_line);
                        TextView textView = (TextView) navLayout.getChildAt(j).findViewById(R.id.text);
                        if(v == navLayout.getChildAt(j)){
                            initRegionList(ids[j], ids[j+1]);
                            baseLine.setVisibility(View.VISIBLE);
                            textView.setTextColor(XYBAUtils.getColor(R.color.red));
                        }else{
                            baseLine.setVisibility(View.GONE);
                            textView.setTextColor(XYBAUtils.getColor(R.color.black));
                        }
                    }
                }
            });
            if(TextUtils.isEmpty(names[i]) || i == names.length-1){
                textView.setTextColor(activity.getResources().getColor(R.color.red));
                layout.findViewById(R.id.base_line).setVisibility(View.VISIBLE);
                break;
            }
        }
    }

    public void init() {
        updateList();
        updateNav();
    }

    public void show(View view){
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if(inputMethodManager != null){
            inputMethodManager.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
        }
//        backgroundAlpha(0.5f);
        showAtLocation(view, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    private void backgroundAlpha(float alpha){
        WindowManager.LayoutParams params = activity.getWindow().getAttributes();
        params.alpha = alpha;
        activity.getWindow().setAttributes(params);
    }
    private Long mCurselectId=null;
    private void initRegionList(Long parentId, final Long selectedId){
        mCurselectId=selectedId;
        regionService.fetchRegionByParentId(parentId);
    }

    @OnItemClick(R2.id.list)
    public void onSelectRegion(int position){
        Region region = regionAdapter.getObject(position);
        ids[region.getType()] = region.getId();
        names[region.getType()] = region.getName();
        if(region.getType() < selectDeep && region.getId() > 0){
            for(int i = region.getType()+1; i < 4; i++){
                ids[i] = null;
                names[i] = null;
            }
            updateList();
        }else{
            regionAdapter.setSelectedId(region.getId());
            regionAdapter.notifyDataSetChanged();
            dismiss();
            if(listener != null){
                Region province = new Region();
                province.setId(ids[1]);
                province.setName(names[1]);

                Region city = new Region();
                if(null!=city) {
                    city.setId(ids[2]);
                    city.setName(names[2]);
                }
                Region district = new Region();
                if(null!=district) {
                    district.setId(ids[3]);
                    district.setName(names[3]);
                }
                listener.onSelectRegion(province, city, district);
            }

        }
        updateNav();
    }

    @Override
    public void setState(int state) {

    }


    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        if(object instanceof Collection){
            if(tClass==Region.class){
                if(regionAdapter == null){
                    regionAdapter = new RegionAdapter(activity, (List<Region>) object);
                    regionList.setAdapter(regionAdapter);
                }else{
                    regionAdapter.setList((List<Region>) object);
                    regionAdapter.notifyDataSetChanged();
                }
                regionAdapter.setSelectedId(mCurselectId);
            }
        }
    }

    @Override
    public void notifyError(String errorCode, String content) {

    }

    @Override
    public void onLoginSuccess() {

    }

    @Override
    public void doSaveAddress() {

    }

    @Override
    public void doDelAddress(Address address) {

    }

    @Override
    public void doSetDefaultAdddress(Address address) {

    }

    public interface OnRegionSelectListener{
        void onSelectRegion(Region province, Region city, Region district);
    }
}
